"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/7/11 8:41
@Description : 
当当网图书搜索数据

"""
import time
import pymysql

from selenium import webdriver
from selenium.webdriver.common.by import By


class DangDang:
    def __init__(self):
        self.firefox = webdriver.Firefox()
        self.firefox.get('http://www.dangdang.com/')
        self.firefox.maximize_window()
        self.connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root',
                                          database='python2511',
                                          charset='utf8')
        # 存储所有图书信息
        self.books = []

    def get_html(self):
        # 获取文本框  填写关键词
        self.firefox.find_element(By.ID, 'key_S').send_keys('python')
        # 获取搜索按钮
        self.firefox.find_element(By.CLASS_NAME, 'button').click()

    def parse_html(self):
        # 滚动网页 获取屏幕总高度
        height = self.firefox.execute_script("return document.body.scrollHeight")
        # 设置移动步长
        step = 200
        for i in range(0, height, step):
            # 实现鼠标的滚动  浏览网页    参数1 x  参数2  y 500px
            self.firefox.execute_script(f'window.scrollTo(0, {i})')
            time.sleep(0.2)
        # 解析网页数据
        li_list = self.firefox.find_elements(By.CSS_SELECTOR, '.bigimg>li')
        for li in li_list:
            # 解析图书条目 或图书信息  名字   现价格   定价
            book = {}
            book['title'] = li.find_element(By.CSS_SELECTOR, '.pic').get_attribute('title')
            book['detail'] = li.find_element(By.CSS_SELECTOR, '.detail').text
            book['search_now_price'] = li.find_element(By.CSS_SELECTOR, '.search_now_price').text
            book['search_pre_price'] = li.find_element(By.CSS_SELECTOR, '.search_pre_price').text
            # 添加图书信息到列表
            self.books.append(book)

        # 点击下一页切换页码
        self.firefox.find_element(By.CSS_SELECTOR, 'li.next').click()

    def save_html(self):
        sql = "INSERT INTO `python2511`.`book`(`title`, `detail`, `search_now_price`, `search_pre_price`) VALUES (%(title)s, %(detail)s, %(search_now_price)s, %(search_pre_price)s)"
        cursor = self.connection.cursor()
        for book in self.books:
            cursor.execute(sql, book)
            self.connection.commit()

    def run(self):
        self.get_html()
        time.sleep(2)
        for i in range(1, 2):
            self.parse_html()
            time.sleep(2)
        self.save_html()


if __name__ == '__main__':
    dang = DangDang()
    dang.run()
